package com.example.lib_ui_base

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


/**
 * 定时器
 * -正序还是倒序 DOWN UP
 * -起始点
 * -启动
 * -暂停
 * -间隔
 */
class WjbTimeUtil {
    private var mStartPoint:Int = 0//起点
    private var mOrder = Order.NONE //顺序
    private var mInterval = 0L //间隔
    private var mCallBack:(WjbTimeUtil,Int)->Unit = {_,_->}  //回调数据
    private lateinit var job: Job  //保存协程开启的job
    var result = true  //设置一个开关，是否启动定时


    fun setStartingPoint(start:Int):WjbTimeUtil{
        mStartPoint = start
        return this
    }

    fun setOrder(order:Order):WjbTimeUtil{
        mOrder = order
        return this
    }

    fun setInterval(interval:Long):WjbTimeUtil{
        mInterval = interval
        return this
    }

    fun setCallback(callback:(WjbTimeUtil,Int)->Unit):WjbTimeUtil{
        mCallBack = callback
        return this
    }

    fun start(){
        job = CoroutineScope(Dispatchers.IO).launch {
            while (isActive){ //判断协程是否出于活跃状态
                delay(mInterval)
                if(mOrder != Order.NONE) {  //需要计数
                    if (mOrder == Order.DOWN) mStartPoint-- else mStartPoint++
                }
                withContext(Dispatchers.Main){
                    mCallBack(this@WjbTimeUtil,mStartPoint)
                }

            }

        }
    }

    fun stop(){
        job.cancel()
    }




    enum class Order{
        DOWN,UP,NONE
    }
}